package com.visionork.android.tai.model;

import java.io.Serializable;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.visionork.android.tai.model.adapter.TaiAdapterBase;

public class Video implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private String title;
	private String urlLink;
	private String youtubeID;
	public void setTitle(String title) {
		this.title = title;
	}

	public String getTitle() {
		return title;
	}

	public void setUrlLink(String urlLink) {
		this.urlLink = urlLink;
	}

	public String getUrlLink() {
		return urlLink;
	}

	@Override
	public boolean equals(Object obj) {
		return getUrlLink().equals(((Video) obj).getUrlLink());
	}

	public String getVideoID() {
		if(youtubeID == null || youtubeID.trim().length() == 0) {
			try {
				Document doc = Jsoup.parse(new URL(urlLink), TaiAdapterBase.TIME_OUT);
				Elements elms = doc.getElementsByTag("embed");
				for (Element elm : elms) {
					if (elm.hasAttr("src")) {
						String src = elm.attr("src");
						Pattern r = Pattern
								.compile("http://www.youtube.com/v/([^\\?]*)\\?");
						Matcher m = r.matcher(src);
						if (m.find()) {
							youtubeID = m.group(1);
							break;
						}
					}
				}				
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
		return youtubeID;
	}

}
